<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\models\system;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "sys_position".
 *
 * @property int $id
 * @property string $name  岗位名称
 * @property string|null $pos_key  岗位标识
 * @property string|null $status  状态
 * @property int|null $list_sort  排序
 * @property string|null $remark  备注
 * @property int|null $create_time
 * @property int|null $update_time
 */
class Position extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName(): string
    {
        return 'sys_position';
    }

    /**
     * {@inheritdoc}
     */
    public function rules(): array
    {
        return [
            [['name'], 'required'],

            [['pos_key', 'remark'], 'default', 'value' => ''],
            ['status', 'default', 'value' => '1'],
            ['list_sort', 'default', 'value' => 10],

            [['name', 'pos_key'], 'trim'],

            ['pos_key', 'match', 'pattern' => '/^[A-Za-z0-9_-]+$/', 'message' => '{attribute}必须是字母、数字、下划线或破折号'],

            [['name', 'pos_key'], 'string', 'max' => 64],
            [['remark'], 'string', 'max' => 250],
            [['list_sort'], 'integer'],
            [['status'], 'in', 'range' => ['0', '1']],

            [['create_time', 'update_time'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels(): array
    {
        return [
            'id' => '岗位Id',
            'name' => '岗位名称',
            'pos_key' => '岗位标识',
            'status' => '状态',
            'list_sort' => '排序',
            'remark' => '备注',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function afterDelete()
    {
        if ($this->id) AdminPos::deleteAll(['pos_id' => $this->id]);
        parent::afterDelete();
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors(): array
    {
        return [
            [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
                ],
                'value' => function () {
                    return time();
                }
            ]
        ];
    }
}
